﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessObject;
using BusinessLogic;
using Utility;
using System.Web.Security;
using System.IO;
namespace WebTeamplate
{
    public partial class Admin_UserDetail : BasePage
    {
        #region Fields
        public string urlList = "User.aspx";
        #endregion

        #region ViewStates
        public string Command
        {

            get
            {
                object o = ViewState["Command"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["Command"] = value; }

        }
        public Guid UserID
        {

            get
            {

                object o = ViewState["UserID"];

                if (o != null) return (Guid)o;

                return Guid.Empty;

                //a default

            }

            set { ViewState["UserID"] = value; }

        }
        #endregion

        #region Init,Loads
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientDefaultButton.SetPageDefaultButton(this.Page, btnSave.ClientID);
            if (!Page.IsPostBack)
            {
                InitParamater();
                LoadRoles();
                CommonFunction.LoadSubCate(drlGender, CommonFunction.DEFAULT_GENDER_CODE, true);
                InitTextControl();
                LoadUserInfor();
                txtName.Focus();
            }

        }
        #endregion

        #region Methos
        private void InitParamater()
        {
            try
            {
                UserID = (Request.QueryString["userid"] == null ? Guid.Empty : new Guid(Request.QueryString["userid"].ToString()));
            }
            catch
            { }
            this.Command = (Request.QueryString["act"] == null ? CommonFunction.DEFAULT_COMMAND_ADD : Request.QueryString["act"].ToString());
        }
        private void LoadUserInfor()
        {
            if (this.Command == CommonFunction.DEFAULT_COMMAND_ADD)
                return;
            UserProfile objProfile = UserProfileUtil.Get(this.applicationName, this.UserID);
            if (objProfile != null)
            {
                txtAddress.Text = objProfile.Address;
                txtBirthDay.Text = ConvertValueObject.ParseString(objProfile.BirthDay);
                txtName.Text = objProfile.Name;
                drlGender.SelectedValue = objProfile.Gender.ToString();
                txtUserName.Attributes.Add("class", "detailedViewTextBox_Disable");// = false;
                txtUserName.Enabled = false;

                MembershipUser user = Membership.GetUser(objProfile.UserId);
                if (user != null)
                {
                    txtUserName.Text = user.UserName;
                    txtEmail.Text = user.Email;
                    if (user.IsApproved)
                        chkIsApproved.Checked = true;
                    else chkIsApproved.Checked = false;
                    if (this.UserloginId.ToString() == user.ProviderUserKey.ToString())
                    {
                        chkIsApproved.Enabled = false;
                    }
                    else
                        chkIsApproved.Enabled = true;
                    /*  if (!Roles.IsUserInRole(this.Page.User.Identity.Name, SystemEnum.SystemRole.SuperAdmin.ToString()) && Roles.IsUserInRole(user.UserName, SystemEnum.SystemRole.SuperAdmin.ToString()))
                      {
                      }*/
                    string[] roles = Roles.GetRolesForUser(txtUserName.Text);
                    CommonFunction.CheckValuesCheckBox(roles, chkRoles);

                }
                refvConfirmPass.Enabled = false;
                refvPassWord.Enabled = false;
                cpvConfirmpass.Enabled = false;
            }
        }
        private void UpdateUser()
        {
            try
            {
                MembershipUser user = Membership.GetUser(txtUserName.Text);
                //check email is exist
                string userNameCheck = Membership.GetUserNameByEmail(txtEmail.Text);
                if (userNameCheck != null && !userNameCheck.Equals(txtUserName.Text))
                {
                    lblErrorMessage.Text = string.Format(Resources.Resource.MESSAGE_EXISTS_ITEM, CommonFunction.GetTextLabel(lblEmail));//Email is exist
                    return;
                }
                user.Email = txtEmail.Text;
                if (chkIsApproved.Checked)
                    user.IsApproved = true;
                else user.IsApproved = false;
                //edit roles
                string[] roles = Roles.GetRolesForUser(txtUserName.Text);
                try
                {
                    Roles.RemoveUserFromRoles(txtUserName.Text, roles);
                }
                catch
                { }
                //Add roles
                foreach (ListItem item in chkRoles.Items)
                {

                    if (item.Selected)
                    {
                        try
                        {
                            Roles.AddUserToRole(txtUserName.Text, item.Text);
                        }
                        catch
                        { }
                    }
                }
                Membership.UpdateUser(user);
                UserProfile objUser = new UserProfile();
                objUser.Address = txtAddress.Text;
                objUser.BirthDay = ConvertValueObject.ParseDateTime(txtBirthDay.Text);
                objUser.LastUpdatedBy = this.userLoginName;
                objUser.LastUpdatedDate = CommonFunction.Now;
                objUser.Gender = ConvertValueObject.ParseInt(drlGender.SelectedValue.ToString());
                objUser.Name = txtName.Text;
                objUser.Phone = string.Empty;
                objUser.UserId = new Guid(user.ProviderUserKey.ToString());
                //
                if (!UserProfileUtil.Update(objUser))
                    lblErrorMessage.Text = Resources.Resource.MESSAGE_UPDATE_ERROR;
                else
                    // lblErrorMessage.Text = Resources.Resource.MESSAGE_UPDATE_SUCCESSFULL;
                    Response.Redirect(GetUrlList());

            }
            catch (MembershipCreateUserException e)
            {
                lblErrorMessage.Text = Resources.Resource.MESSAGE_UPDATE_ERROR;
            }
        }

        private void InitTextControl()
        {
            //  imgBirthDay.Attributes.Add("onclick", "displayCalendar('../calendar/images/',document.forms[0]." + txtBirthDay.ClientID + ",'" + BaseFunctions.DEFAULT_DATE_FORMAT + "',this)");
            string validateGroup = "user";
            btnSave.Text = Resources.Resource.LABEL_BUTTON_SAVE;
            btnCacel.Text = Resources.Resource.LABEL_BUTTON_CANCEL;
            refvName.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblName));
            refvName.ValidationGroup = validateGroup;
            refvUserName.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblUserName));
            refvUserName.ValidationGroup = validateGroup;
            refvPassWord.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblPassword));
            refvPassWord.ValidationGroup = validateGroup;
            regvPassword.ValidationGroup = "\\w{" + (Membership.Provider.MinRequiredPasswordLength).ToString() + ",}";
            regvPassword.ValidationGroup = validateGroup;
            regvPassword.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_LENGTH, CommonFunction.GetTextLabel(lblPassword), Membership.Provider.MinRequiredPasswordLength - 1);
            refvConfirmPass.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblConfirmPassword));
            refvConfirmPass.ValidationGroup = validateGroup;
            cpvConfirmpass.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_COMPARE, CommonFunction.GetTextLabel(lblConfirmPassword), CommonFunction.GetTextLabel(lblPassword));
            cpvConfirmpass.ValidationGroup = validateGroup;
            regvEmail.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblEmail));
            regvEmail.ValidationGroup = validateGroup;
           // cusvEmail.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblEmail));
           // cusvEmail.ValidationGroup = validateGroup;
           // refvBirthDay.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblBirthDay));
           // refvBirthDay.ValidationGroup = validateGroup;
            cusvBirthDay.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblBirthDay));
            cusvBirthDay.ValidationGroup = validateGroup;
            refvGender.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblGender));
            refvGender.ValidationGroup = validateGroup;
           // refvAddress.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblAddress));
           // refvAddress.ValidationGroup = validateGroup;
            vsumCategory.ValidationGroup = validateGroup;
            btnSave.ValidationGroup = validateGroup;
            // lblPublish.Text = Resources.Resource.LABEL_PUBLISH;

        }
        private void CreateMembership()
        {
            try
            {
                
                MembershipUser user = Membership.CreateUser(txtUserName.Text, txtPassword.Text);
                if (!chkIsApproved.Checked)
                {
                    user.IsApproved = false;
                    Membership.UpdateUser(user);
                }
                //Add roles
                foreach (ListItem item in chkRoles.Items)
                {
                    if (item.Selected)
                    {
                        Roles.AddUserToRole(txtUserName.Text, item.Text);
                    }
                }
                UserProfile objUser = new UserProfile();
                objUser.Address = txtAddress.Text;
                objUser.BirthDay = ConvertValueObject.ParseDateTime(txtBirthDay.Text);
                objUser.CreatedBy = objUser.LastUpdatedBy = this.userLoginName;
                objUser.CreatedDate = objUser.LastUpdatedDate = CommonFunction.Now;
                objUser.Gender = ConvertValueObject.ParseInt(drlGender.SelectedValue.ToString());
                objUser.Name = txtName.Text;
                objUser.Phone = string.Empty;
                objUser.UserId = new Guid(user.ProviderUserKey.ToString());
                //
                if (!UserProfileUtil.Insert(objUser))
                {
                    //Delete Role
                    Roles.RemoveUserFromRoles(txtUserName.Text, Roles.GetRolesForUser(txtUserName.Text));
                    //Delete USer
                    Membership.DeleteUser(txtUserName.Text);
                    lblErrorMessage.Text = Resources.Resource.MESSAGE_INSERT_ERROR;
                    return;
                }
                else
                {
                    if (CommonFunction.DEFAULT_SENDMAIL_CREATE_USER)
                        SendMailToUser(objUser);
                    Response.Redirect(GetUrlList());
                }

            }
            catch (MembershipCreateUserException e)
            {
                lblErrorMessage.Text = ErrorCodeToString(e.StatusCode);
            }
        }
        private void SendMailToUser(UserProfile user)
        {
            string mailBody = string.Empty;
            string title = string.Empty;
            GetMailTemplate(ref mailBody, ref title);
            if (mailBody != string.Empty)
                BaseFunctions.SendMail(CommonFunction.DEFAULT_MAILFROM, txtEmail.Text, title, mailBody, CommonFunction.DEFAULT_MAIL_SERVER_NAME, CommonFunction.DEFAULT_MAIL_SERVER_PORT);

        }
        private void GetMailTemplate(ref string body, ref string title)
        {
            string filePath = Server.MapPath("~/Admin/TemplateMail" + "\\" + CommonFunction.DEFAULT_CREATE_USER_TEMPLATE);
            if (File.Exists(filePath))
            {
                string[] text = File.ReadAllLines(filePath);
                title = text.GetValue(0).ToString();
                for (int i = 1; i < text.Length; i++)
                {
                    body += text.GetValue(i).ToString() + "\r\n";
                }
                body = string.Format(body, txtName.Text, txtUserName.Text, txtPassword.Text);
            }
        }
        private string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return string.Format(Resources.Resource.MESSAGE_EXISTS_ITEM, CommonFunction.GetTextLabel(lblUserName));

                case MembershipCreateStatus.DuplicateEmail:
                    return string.Format(Resources.Resource.MESSAGE_EXISTS_ITEM, CommonFunction.GetTextLabel(lblEmail));

                case MembershipCreateStatus.InvalidPassword:
                    return string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblPassword));

                case MembershipCreateStatus.InvalidEmail:
                    return string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblEmail));

                case MembershipCreateStatus.InvalidUserName:
                    return string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblUserName));

                default:
                    return Resources.Resource.MESSAGE_INSERT_ERROR;
            }
        }
        private void LoadRoles()
        {
            chkRoles.Items.Clear();
            string[] roles = Roles.GetAllRoles();
            if (roles.Length > 0)
            {
                Vw_aspnet_RolesResult objRoleMax = UserProfileUtil.GetMaxRole(this.userloginId, this.applicationName);
                foreach (string role in roles)
                {
                    Vw_aspnet_RolesResult objRole = UserProfileUtil.GetRoleByName(this.applicationName,role);
                    if(objRole.Level<=objRoleMax.Level)
                    chkRoles.Items.Add(new ListItem(role, role));
                }

                //if (Roles.IsUserInRole(this.Page.User.Identity.Name, SystemEnum.SystemRole.SuperAdmin.ToString()))
                //{
                //    foreach (string role in roles)
                //    {                        
                //            chkRoles.Items.Add(new ListItem(role, role));
                //    }
                //}
                //else
                //{
                //    foreach (string role in roles)
                //    {
                //        if (role != SystemEnum.SystemRole.SuperAdmin.ToString())
                //            chkRoles.Items.Add(new ListItem(role, role));
                //    }
                //}
            }
        }
        private string GetUrlList()
        {
            return urlList;
        }
        #endregion

        #region Events, Handler
        protected void btnCacel_Click(object sender, EventArgs e)
        {
            Response.Redirect(GetUrlList());
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (this.Command == CommonFunction.DEFAULT_COMMAND_ADD)
                    CreateMembership();
                else
                    UpdateUser();
            }
            else
            {
                vsumCategory.ShowMessageBox = false;
                vsumCategory.ShowSummary = true;
            }
        }
        #endregion
    }
}
